/**
 * Copyright (c) 2004-2016 All Rights Reserved.
 */
package com.zbest.zpay.gw.assemble;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import com.zbest.zpay.gw.assemble.alipay.CreateForexTradeAssemble;
import com.zbest.zpay.gw.assemble.wx.UnifiedorderAssemble;
import com.zbest.zpay.gw.dal.dao.GwTransactionContentDAO;
import com.zbest.zpay.gw.dal.model.GwTransactionContentDO;
import com.zbest.zpay.gw.model.MessageContext;
import com.zbest.zpay.service.gw.model.GwKeyEnum;

/**
 * 
 *
 * @author czhou3306@gmail.com
 * @version $Id: MessageAssembleManagerImpl.java, v0.1 2016年4月4日 下午2:07:23
 *          czhou3306@gmail.com Exp $
 */
@Service("messageAssembleManager")
public class MessageAssembleManager implements InitializingBean {

    private Map<String, MessageAssemble> assembleMap       = new HashMap<String, MessageAssemble>();

    private List<String>                 channelIdNeedSave = new ArrayList<String>();

    @Resource
    private CreateForexTradeAssemble     createForexTradeAssemble;

    @Resource
    private UnifiedorderAssemble         unifiedorderAssemble;

    @Resource
    private DefaultMessageAssemble       defaultMessageAssemble;

    @Resource
    private GwTransactionContentDAO      gwTransactionContentDAO;

    /**
     * @see com.zbest.zpay.gw.assemble.MessageAssembleManager#assemble(java.lang.String,
     *      java.lang.String, java.util.Map)
     */
    public void assemble(MessageContext context) {

        MessageAssemble messageAssemble = assembleMap.get(context.getChannelId());
        if (messageAssemble == null) {
            messageAssemble = defaultMessageAssemble;
        }
        messageAssemble.buildRequest(context);

        // if (channelIdNeedSave.contains(context.getChannelId())) {
        saveSendMessage(context);
        //}

    }

    /**
     * 保存报文
     * 
     * @param context
     */
    private void saveSendMessage(MessageContext context) {
        GwTransactionContentDO gwTransactionContentDO = new GwTransactionContentDO();
        gwTransactionContentDO.setChannelId(context.getChannelId());
        String instSerialNo = context.getRequestData(GwKeyEnum.INST_SERIAL_NO.getCode());
        gwTransactionContentDO.setInstSerialNo(instSerialNo);
        gwTransactionContentDO.setRequestContent(context.getSendMessage().toString());
        gwTransactionContentDAO.insert(gwTransactionContentDO);
    }

    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        assembleMap.put("ALIPAYGJ001", createForexTradeAssemble);

        assembleMap.put("WXGJ001", unifiedorderAssemble);

        channelIdNeedSave.add("ALIPAYGJ001");
    }
}
